﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Cashbook.Models;
using Cashbook.Services;
using Xamarin.Forms;

namespace Cashbook.Views
{
    public partial class CustomersPage : ContentPage
    {
        private CustomersDataAccess dataAccess;
		
        public CustomersPage()
        {
            InitializeComponent();
            this.dataAccess = new CustomersDataAccess();

		}
		protected override async void OnAppearing()
		{
			base.OnAppearing();
			// The instance of CustomersDataAccess
			// is the data binding source
            this.dataAccess.Customers = await dataAccess.GetCustomersOC();
			this.BindingContext = this.dataAccess;
		}

		public void OnEdit(object sender, EventArgs e)
		{
			var mi = ((MenuItem)sender);

            int customerId;
            if (int.TryParse(mi.CommandParameter.ToString(), out customerId))
            {
                Navigation.PushAsync(new EditCustomerPage(customerId));
            }
            else{
                DisplayAlert("编辑客户资料", "没有找到当前所选项", "确定");
            };

			//
		}

		public async void OnDelete(object sender, EventArgs e)
		{
			var mi = ((MenuItem)sender);
			int customerId;
			if (int.TryParse(mi.CommandParameter.ToString(), out customerId))
			{
				var result = await DisplayAlert("删除客户", "您确定要删除当前所选客户吗，此操作不可恢复？", "确定", "取消");
				if (result)
				{
                    var customer = await this.dataAccess.GetCustomerAsync(customerId);
                    var isDelete = await this.dataAccess.DeleteCustomerAsync(customer);
                    if(isDelete>0){
                        this.dataAccess.Customers = await this.dataAccess.GetCustomersOC();
                        CustomersView.ItemsSource = this.dataAccess.Customers;
                    }
				}
			}
			else
			{
                await DisplayAlert("删除客户资料", "没有找到当前所选项", "确定");
			};


		}

		// async void OnItemSelected(object sender, SelectedItemChangedEventArgs args)
		//{
		//var item = args.SelectedItem as Item;
		//if (item == null)
		//    return;

		//await Navigation.PushAsync(new ItemDetailPage(new ItemDetailViewModel(item)));

		// Manually deselect item
		//ItemsListView.SelectedItem = null;
		//}

		async void AddItem_Clicked(object sender, EventArgs e)
		{
			await Navigation.PushAsync(new EditCustomerPage(0));
		}


        void Handle_ItemTapped(object sender, Xamarin.Forms.ItemTappedEventArgs e)
        {
			if (e.Item == null) return;
			// do something with e.SelectedItem
			((ListView)sender).SelectedItem = null; // de-select the row
		}
    }
}
